﻿using GamFi.API.Application.Contracts.Token.GetTokens;
using GamFi.API.Application.Exceptions;
using GamFi.API.Application.Interfaces;
using GamFi.API.Application.Resources;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;

namespace GamFi.API.Application.Features.Queries.Token.GetTokens;

public class GetTokensQueryHandler(IDbContext dbContext, IStringLocalizer<ExceptionMessages> localizer)
    : IRequestHandler<GetTokensQuery, GetTokensResponse>
{
    public async Task<GetTokensResponse> Handle(GetTokensQuery request, CancellationToken cancellationToken)
    {
        if (request is null)
            throw new RequestException(localizer[nameof(RequestException.RequestIsEmpty)]);
        
        var query = dbContext.Tokens
            .AsQueryable();

        if (!string.IsNullOrEmpty(request.Filter))
            query = query.Where(u => u.Name.ToLower().Contains(request.Filter.ToLower()));

        query = query
            .Skip((request.PageNumber - 1) * request.PageSize)
            .Take(request.PageSize);

        var tokens = await query.Select(t =>
            new GetTokensResponseItem
            {
                Id = t.Id,
                Name = t.Name,
                TokenSymbol = t.TokenSymbol,
                CreatedDate = t.CreatedDate ?? DateTime.MinValue,
                CreatedBy = t.CreatedBy ?? Guid.Empty,
                ChainId = t.ChainId,
                TargetedRaise = t.TargetedRaise,
                TotalRaise = t.TotalRaise,
                ImageId = t.ImageId
            }).ToListAsync(cancellationToken);

        return new GetTokensResponse
        {
            Tokens = tokens,
            Count = tokens.Count
        };
    }
}